(function($) {

	// Get Loader
	$.fn.showLoader = function() {
		return $(this).html('<h1><i class="fa fa-spinner fa-spin"></i></h1>').css({ 'position' : 'absolute', 'z-index': 3, 'right' : 0, 'left' : 0, 'top' : '40%', 'text-align' : 'center' });
	};

	// Get List View
	$.fn.showList = function( url ) {
		var base = this;
		var url = ( typeof url  !== "undefined" && url != '' ) ? url :  document.URL;

		$.ajax({
			url: url,
			dataType: 'html',
			beforeSend: function() {
				$(base).css({ 'opacity' : '.5'}).find('.loader').showLoader();
			},
			complete: function() { $(base).css({ 'opacity' : '1'})},
			success: function(html) {
				$(base).html(html).showEditForm().showView();
				$('ul.pagination a').click(function(e){
					e.preventDefault();
					$(base).showList($(this).attr('href'));

					if( history.pushState ) {
						history.pushState(null, null, $(this).attr('href'));
					}

				});
				$('a.remove').showDestroyConfirmation( base );
				$('a#filter').filterList( base );
			}
		});	
		
		return base;
	};

	// Filter List
	$.fn.filterList = function( option ) {
		var base = this;
		var list = ( typeof option  !== "undefined" && option != '' ) ? option :  'div#list-container';
		var form = $(base).parents("form");

		$(this).click(function(e){
			e.preventDefault();			
			$(list).showList($(this).attr('href') + '?' + form.serialize());
			if( history.pushState ) {
				history.pushState(null, null, $(this).attr('href') + '?' + form.serialize());
			}			
		});
		return base;
	};

	// Destroy Data
	$.fn.showDestroyConfirmation = function(list) {
		var base = this;
		$(this).click(function(e) {
			e.preventDefault();
			var part = $(this).attr('id').split('-id-');
			var html  = '<div class="text-center">';
				html += '<p class="lead">Are you sure you want to remove this record?</p>';
				html += '<a class="btn btn-info" href="#" data-dismiss="modal" id="confirm-remove">CONTINUE</a> ';
				html += '</div>';

			$("#general-modal .modal-body").html(html);
			$("#general-modal-label").html('<span class="glyphicon glyphicon-question-sign"></span> Confirmation');
			$("#general-modal").modal('show');
			
			$("#confirm-remove").click(function(e){
				e.preventDefault();
				var token = $('#csrf-token').attr('content');

				$.ajax({
					url: $('base').attr('href') + '/'  + part[0] + '/' + part[1],
					type: 'POST',
					data: {_token : token ,_method: 'delete', id : part[1]},
					success: function(response) {
						$(list).showList(document.URL);
						$("div#form-container").html('');
					},
					error: function (a,b,c) {

					}
				});				
			});


		});
	};

	// Get Edit Form
	$.fn.showEditForm = function(option) {
		var base = this;
		var form = ( typeof option  !== "undefined" && option != '' ) ? option :  'div#form-container';

		$(this).find('a.edit').click(function(e){
			e.preventDefault();
			var url = $(this).attr('href');
			if (typeof url  !== "undefined") {
				$.ajax({
					url: url,
					dataType: 'html',
					beforeSend: function() { $(form).css({ 'opacity' : '.5'}).find('.loader').showLoader(); },
					complete: function() { $(form).css({ 'opacity' : '1'})},
					success: function(html) {
						// Hide Side Navigation if active
						var nav_left = $('#column-left');
						
						if ( nav_left.hasClass('active') ) {
							nav_left.find('ul#menu').find('li').removeClass('active');
							nav_left.removeClass('active').removeClass('open');
						}
					
						// Make #list-column to be #list-container parent
						var list_column = $("div#list-container").parent().attr('id', 'list-column');
						
						// Remove 12 cols class and Add 6 cols class in #list-column
						list_column.removeClass('col-lg-12 col-md-12 col-sm-12');
						list_column.addClass('col-lg-6 col-md-6 col-sm-6'); //.hide().fadeIn('fast');
						
						// Make #form-column to be #form-container parent
						var form_column = $(form).parent().attr('id', 'form-column');
						
						// Remove 12 cols class and Add 6 cols class in #form-column
						form_column.removeClass('col-lg-12 col-md-12 col-sm-12');
						form_column.addClass('col-lg-6 col-md-6 col-sm-6 pull-right');
							
						// Activate #form-container and animate.
						$(form).addClass('animated fadeInRight active');
						
						// Add Content to #form-container
						$(form).html(html);
						
						$(form + " input[type='submit']").submitForm(form);
					}
				});
			}
			else {
				$(form).html('Error Getting Update Form');
			}
		});

		return base;
	};

	// Get Add Form
	$.fn.showAddForm = function(option) {
		var base = this;
		var form = ( typeof option  !== "undefined" && option != '' ) ? option :  'div#form-container';

		$(this).click(function(e){
			e.preventDefault();
			var url = $(this).attr('href');
			if (typeof url  !== "undefined") {
				$.ajax({
					url: url,
					dataType: 'html',
					beforeSend: function() { $(form).css({ 'opacity' : '.5'}).find('.loader').showLoader(); },
					complete: function() { $(form).css({ 'opacity' : '1'})},
					success: function(html) {
						// Hide Side Navigation if active
						var nav_left = $('#column-left');
						
						if ( nav_left.hasClass('active') ) {
							nav_left.find('ul#menu').find('li').removeClass('active');
							nav_left.removeClass('active').removeClass('open');
						}
	
						// Make #list-column to be #list-container parent
						var list_column = $("div#list-container").parent().attr('id', 'list-column');
						
						// Remove 12 cols class and Add 6 cols class in #list-column
						list_column.removeClass('col-lg-12 col-md-12 col-sm-12');
						list_column.addClass('col-lg-6 col-md-6 col-sm-6'); //.hide().fadeIn('fast');
						
						// Make #form-column to be #form-container parent
						var form_column = $(form).parent().attr('id', 'form-column');
						
						// Remove 12 cols class and Add 6 cols class in #form-column
						form_column.removeClass('col-lg-12 col-md-12 col-sm-12');
						form_column.addClass('col-lg-6 col-md-6 col-sm-6 pull-right');
							
						// Activate #form-container and animate.
						$(form).addClass('animated fadeInRight active');
						
						// Add Content to #form-container
						$(form).html(html);
						
						$(form + " input[type='submit']").submitForm(form);
					}
				});
			}
			else {
				$(form).html('Error Getting Create Form');
			}
		});
		return this;
	};
	
	
	// Get Show View
	$.fn.showView = function(option) {
		var base = this;
		var form = ( typeof option  !== "undefined" && option != '' ) ? option :  'div#form-container';

		$(this).find('a.show').click(function(e){
			e.preventDefault();
			var url = $(this).attr('href');
			if (typeof url  !== "undefined") {
				$.ajax({
					url: url,
					dataType: 'html',
					beforeSend: function() { $(form).css({ 'opacity' : '.5'}).find('.loader').showLoader(); },
					complete: function() { $(form).css({ 'opacity' : '1'})},
					success: function(html) {
						// Hide Side Navigation if active
						var nav_left = $('#column-left');
						
						if ( nav_left.hasClass('active') ) {
							nav_left.find('ul#menu').find('li').removeClass('active');
							nav_left.removeClass('active').removeClass('open');
						}
					
						// Make #list-column to be #list-container parent
						var list_column = $("div#list-container").parent().attr('id', 'list-column');
						
						// Remove 12 cols class and Add 6 cols class in #list-column
						list_column.removeClass('col-lg-12 col-md-12 col-sm-12');
						list_column.addClass('col-lg-6 col-md-6 col-sm-6'); //.hide().fadeIn('fast');
						
						// Make #form-column to be #form-container parent
						var form_column = $(form).parent().attr('id', 'form-column');
						
						// Remove 12 cols class and Add 6 cols class in #form-column
						form_column.removeClass('col-lg-12 col-md-12 col-sm-12');
						form_column.addClass('col-lg-6 col-md-6 col-sm-6 pull-right');
							
						// Activate #form-container and animate.
						$(form).addClass('animated fadeInRight active');
						
						// Add Content to #form-container
						$(form).html(html);
					}
				});
			}
			else {
				$(form).html('Error Getting Update Form');
			}
		});

		return base;
	};

	// Ajax POST method to pass form data
	$.fn.submitForm = function(option) {

		// Initialize Cancel Button Action
		$("a#cancel").cancelForm(option);

    	var base = this;
		$(this).click(function(e){
		    e.preventDefault();

		    // Button
		    var btn 	= $(this);

		    // Form
		    var form 	= $(option + " form");

		    // Form URL
		    var url 	= form.attr('action');

		    // URI Segments of URL
		    var uri 	= String(url).split('/');

		    // Default Submit Method
			var method	= 'POST';

			// If URL doesn't have ID ( If action is 'Edit')
		    if(!isNaN(uri[uri.length-1])) {
		        method = 'PUT';
		    }

		    if( method == 'PUT') {

		    }

		    btn.button('loading');

		     $.ajax({
				url: url,
				type: method,
		        data: new FormData( form[0] ),
		        cache: false,
		        contentType: false,
		        processData: false,	
				dataType: 'json',
				beforeSend: function() { $(option).css({ 'opacity' : '.5'}).find('.loader').showLoader(); },
				complete: function() { $(option).css({ 'opacity' : '1'}); $(option + " .loader").remove();},

		        // Success
				success: function(json) {

					// Show View
					if ( typeof json['show']  !== "undefined" ) {
						$.ajax({
							url: json['show'],
							dataType: 'html',
							beforeSend: function() { $(form).css({ 'opacity' : '.5'}).find('.loader').showLoader(); },
							complete: function() { $(form).css({ 'opacity' : '1'})},
							success: function(html) {
								// Show Edit Form
								$(option).html(html).showEditForm();

								// Show List
								$('div#list-container').showList(document.URL);
							}
						});

					} else {
						$('.error').html('');
						
						if ( json['error'] ) {
							$.each(json['error'], function(key, row){
								var error = '';

								$.each(row, function(index, result) {
									
									if (isNaN(result.length)){
										
										// Getting Sub Error
										$.each(result, function(key_sub, row_sub) {

											var error_sub = '';

											$.each(row_sub, function(index_sub, result_sub) {
												error_sub += '<p>' + result_sub + '</p>';
											});

											$('#error_' + key + '_' + index + '_' + key_sub).html( error_sub );
										});

									} else {
										error += '<p>' + result + '</p>';
										
									}

								});

								$('#error_' + key).html( error );
							});
						} else {
							$(option).html("Error Fetching Result");
						}

					}

				}
		     }).always(function() { btn.button('reset'); });

		    return false;       
		});
	};

	// Cancel Form
	$.fn.cancelForm = function( option, url ) {
		var base = this;
		var url = ( typeof url  !== "undefined" && url != '' ) ? url :  document.URL;

		$(this).click(function(e) {
			e.preventDefault();
			/*
			var html  = '<div class="alert alert-warning"><i class="fa fa-check-circle"></i> Transaction has been cancelled';
				html +=	'<button type="button" class="close" data-dismiss="alert">&times;</button>';
				html += '</div>';

			$(option).html(html);*/
		
			// Remove Form content
			$(option).html('');
			
			// Make #list-column to be #list-container parent
			var list_column = $("div#list-container").parent().attr('id', 'list-column');
			
			// Remove 6 cols class and Add 12 cols class in #list-column
			list_column.removeClass('col-lg-6 col-md-6 col-sm-6');
			list_column.addClass('col-lg-12 col-md-12 col-sm-12');
			
			// Make #form-column to be #form-container parent
			var form_column = $(option).parent().attr('id', 'form-column');
			
			// Remove 6 cols class and Add 12 cols class in #form-column
			form_column.addClass('col-lg-6 col-md-6 col-sm-6 pull-right');
			form_column.removeClass('col-lg-12 col-md-12 col-sm-12');
				
			// Deactivate #form-container and remove animate.
			$(option).removeClass('animated fadeInRight active');
		});
		return this;
	};

}(jQuery));